<template>
  <div class="body1">
    <div class="no-print el-button-print">
      <el-dropdown trigger="click">
        <el-button style="margin-right: 20px;">设置</el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-for="(option, index) in options" :key="index" @click="selectOption(option)">
              {{ option.b }}</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button @click="exportPDF">导出为pdf</el-button>
    </div>
    <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
      <div v-for="(item, index) in form" :key="index" :class="{ 'page-break': index !== 0 }">

        <div class="title">
          <div class="biaotididian">{{ agencyName }}</div>
          <div class="biaoti">身份证件（或统一社会信用代码）照片</div>
        </div>
        <table class="tableStyle" v-show="table1">
          <tr>
            <td>
              <div style="display: flex; align-items: center; justify-content: center; height: 280px;"
                class="image-container" @click="chooseImage(index)">
                <img v-if="!isLoading && item.imageSrc" :src="item.imageSrc" alt="统一社会信用代码照片"
                  style="max-height: 99%; max-width: 99%;">
                <input type="file" accept="image/*" style="display: none" ref="imageInput" @change="handleFileChange">
                <div v-if="!item.imageSrc || isLoading" class="placeholder-image">统一社会信用代码照片
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>
              <div style="display: flex; align-items: center; justify-content: center;  height: 280px;"
                class="image-container" @click="chooseImage1(index)">
                <img v-if="!isLoading1 && item.imageSrc1" :src="item.imageSrc1" alt="身份证正面（国徽面）照片"
                  style="max-height: 99%; max-width: 99%;">
                <input type="file" accept="image/*" style="display: none" ref="imageInput1" @change="handleFileChange1">
                <div v-if="!item.imageSrc1 || isLoading1" class="placeholder-image">
                  身份证正面（国徽面）照片
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>
              <div style="display: flex; align-items: center; justify-content: center;  height: 280px;"
                class="image-container" @click="chooseImage2(index)">
                <img v-if="!isLoading2 && item.imageSrc2" :src="item.imageSrc2" alt="身份证背面（人像面）照片"
                  style="max-height: 99%; max-width: 99%;">
                <input type="file" accept="image/*" style="display: none" ref="imageInput2" @change="handleFileChange2">
                <div v-if="!item.imageSrc2 || isLoading2" class="placeholder-image">
                  身份证背面（人像面）照片

                </div>
              </div>
            </td>
          </tr>
        </table>
        <table class="tableStyle" v-show="table2">
          <tr>
            <td>
              <div style="display: flex; align-items: center; justify-content: center;  height: 420px;"
                class="image-container" @click="chooseImage1(index)">
                <img v-if="!isLoading1 && item.imageSrc1" :src="item.imageSrc1" alt="身份证正面（国徽面）照片"
                  style="max-height: 99%; max-width: 99%;">
                <input type="file" accept="image/*" style="display: none" ref="imageInput1" @change="handleFileChange1">
                <div v-if="!item.imageSrc1 || isLoading1" class="placeholder-image1">
                  身份证正面（国徽面）照片
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>
              <div style="display: flex; align-items: center; justify-content: center;  height: 420px;"
                class="image-container" @click="chooseImage2(index)">
                <img v-if="!isLoading2 && item.imageSrc2" :src="item.imageSrc2" alt="身份证背面（人像面）照片"
                  style="max-height: 99%; max-width: 99%;">
                <input type="file" accept="image/*" style="display: none" ref="imageInput2" @change="handleFileChange2">
                <div v-if="!item.imageSrc2 || isLoading2" class="placeholder-image1">
                  身份证背面（人像面）照片
                </div>
              </div>
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import SignTemblate from "@/views/SignTemblate.vue";
import { agencyName, sealName } from "../../utils/publicName.js"
export default {
  components: { SignTemblate },

  props: {
    currentSignType: String
  },

  mounted() {
    this.signType = this.currentSignType;
    debugger
    window.parent.changeTemplateDow();
  },

  data() {
    return {
      agencyName: agencyName,
      sealName: sealName,
      isLoading: false,
      isLoading1: false,
      isLoading2: false,
      imageSrc: null,
      imageSrc1: null,
      imageSrc2: null,
      isPdfExport: false, // 控制打印样式

      paraName: "",
      paramtype: "",
      resultImgurl: '',
      signType: '',
      currentItem: {},
      form: [{
        mark: 1,
      }],
      options: [
        {
          a: 1,
          b: '单位'
        },
        {
          a: 2,
          b: '个人'
        }
      ],
      table1: true,
      table2: false,
    };
  },
  created() {
    //调用父页面函数获取文书数据
    window.parent.getTemplateData((data) => {
      this.form = data;
      debugger
      if (this.form[0].mark == 1) {
        debugger
        this.table1 = true;
        this.table2 = false;
      } else if (this.form[0].mark == 2) {
        this.table1 = false;
        this.table2 = true;
      }
    })
    //将方法暴露在初始化加载中
    window.postForm = () => {
      debugger
      this.postForm();
    }
  },


  methods: {
    // 导出为pdf
    exportPDF() {
      this.savePDF()
        .then((blob) => {
          const blobUrl = URL.createObjectURL(blob);

          // 先预览
          const previewWindow = window.open(blobUrl, '_blank');

          // 自动下载
          const fileName = `身份证件（或统一社会信用代码）照片.pdf`;
          const downloadLink = document.createElement('a');
          downloadLink.href = blobUrl;
          downloadLink.download = fileName;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);

          // 监听预览窗口关闭后释放内存
          if (previewWindow) {
            const timer = setInterval(() => {
              if (previewWindow.closed) {
                clearInterval(timer);
                URL.revokeObjectURL(blobUrl);
              }
            }, 1000);
          } else {
            setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
          }
        })
        .catch(error => {
          console.error('导出PDF出错:', error);
          alert('导出失败，请重试或联系管理员');
        });
    },
    savePDF() {
      this.isPdfExport = true; // 激活PDF样式
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          import('html2pdf.js').then((module) => {
            const html2pdf = module.default;

            //获取所有需要替换的 el-input
            const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

            //存储原始元素和它们的父节点，方便后续恢复
            const originalElements = [];

            elInputs.forEach((input) => {
              const div = document.createElement('div');
              div.style.whiteSpace = 'pre-wrap'; // 保留换行
              div.style.fontFamily = '仿宋';
              div.style.fontSize = '5mm';
              div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
              div.style.lineHeight = '1.3';

              // 替换 el-input，并存储原始元素
              originalElements.push({
                parent: input.parentNode,
                original: input,
                replacement: div,
              });
              input.parentNode.replaceChild(div, input);
            });

            // 配置选项
            const opt = {
              margin: 0,
              image: {
                type: 'jpeg',
                quality: 0.98
              },
              html2canvas: {
                scale: 2,
                logging: false,
                useCORS: true
              },
              jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
              }
            };

            const element = document.getElementById('pdfDom');

            // 生成PDF Blob对象
            html2pdf()
              .set(opt)
              .from(element)
              .toPdf()
              .get('pdf')
              .then((pdf) => {
                const blob = pdf.output('blob');

                resolve(blob); // 返回Blob对象
              })
              .catch((error) => {
                reject(error);
              })
              .finally(() => {
                this.isPdfExport = false; // 恢复原始样式
                // 恢复原始input
                originalElements.forEach(({ parent, original, replacement }) => {
                  parent.replaceChild(original, replacement);
                });
              });
          }).catch((error) => {
            reject(error);
            this.isPdfExport = false;
            originalElements.forEach(({ parent, original, replacement }) => {
              parent.replaceChild(original, replacement);
            });
          });
        });
      });
    },
    //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
    postForm() {
      this.savePDF()
        .then((blob) => {


          // 创建FormData并添加文件
          const formData = new FormData();
          formData.append('file', blob, '身份证件（或统一社会信用代码）照片.pdf');

          window.parent.postTemplateDate(this.form, formData);
        })
        .catch(error => {
          console.error('整个保存PDF出错:', error);
        });
    },

    selectOption(selectedOption) {
      if (selectedOption.a == 1) {
        this.table1 = true;
        this.table2 = false;
        this.form[0].mark = 1;
      } else if (selectedOption.a == 2) {
        this.table1 = false;
        this.table2 = true;
        this.form[0].mark = 2;
      }
    },

    chooseImage(index) {
      this.currentItem = this.form.at(index)
      this.$refs["imageInput"][index].click();
    },

    async handleFileChange(event) {
      try {
        // debugger;
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.onload = () => {
          this.currentItem.imageSrc = reader.result;
        };

        if (file) {

          this.isLoading = true;
          reader.readAsDataURL(file);
          setTimeout(() => {
            this.isLoading = false;
          }, 2000);

          const formData = new FormData();
          // 添加 file 属性，并指定文件名
          formData.append('file', file);

          // 设置 Content-Type 头部为 multipart/form-data
          const config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };

          const response = await axios.post('/api/related-file/uploadSign', formData, config);
          const { code, data, message } = response.data;
          if (code === '200') {
            if (data && data.url) {
              // debugger;
              this.resultImgurl = data.url;
              this.resultImgname = data.name;
            } else {
              throw new Error('图片上传失败，请重试！');
            }
          } else {
            throw new Error(message || '图片上传失败，请重试！');
          }
          const url = `api/file/download/${this.resultImgurl}`;
          this.currentItem.imageSrc = url
        }
      } catch (err) {
        this.$emit('updateSignImg', '', this.signType);
      }
    },

    chooseImage1(index) {
      this.currentItem = this.form.at(index)
      this.$refs["imageInput1"][index].click();
    },

    async handleFileChange1(event) {
      try {
        // debugger;
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.onload = () => {
          this.currentItem.imageSrc1 = reader.result;
        };

        if (file) {

          this.isLoading1 = true;
          reader.readAsDataURL(file);
          setTimeout(() => {
            this.isLoading1 = false;
          }, 2000);

          const formData = new FormData();
          // 添加 file 属性，并指定文件名
          formData.append('file', file);

          // 设置 Content-Type 头部为 multipart/form-data
          const config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };

          const response = await axios.post('/api/related-file/uploadSign', formData, config);
          const { code, data, message } = response.data;
          if (code === '200') {
            if (data && data.url) {
              // debugger;
              this.resultImgurl = data.url;
              this.resultImgname = data.name;
            } else {
              throw new Error('图片上传失败，请重试！');
            }
          } else {
            throw new Error(message || '图片上传失败，请重试！');
          }
          const url = `api/file/download/${this.resultImgurl}`;
          this.currentItem.imageSrc1 = url
        }
      } catch (err) {
        this.$emit('updateSignImg', '', this.signType);
      }
    },

    chooseImage2(index) {
      this.currentItem = this.form.at(index)
      this.$refs["imageInput2"][index].click();
    },

    async handleFileChange2(event) {
      try {
        // debugger;
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.onload = () => {
          this.currentItem.imageSrc2 = reader.result;
        };

        if (file) {

          this.isLoading2 = true;
          reader.readAsDataURL(file);
          setTimeout(() => {
            this.isLoading2 = false;
          }, 2000);

          const formData = new FormData();
          // 添加 file 属性，并指定文件名
          formData.append('file', file);

          // 设置 Content-Type 头部为 multipart/form-data
          const config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };

          const response = await axios.post('/api/related-file/uploadSign', formData, config);
          const { code, data, message } = response.data;
          if (code === '200') {
            if (data && data.url) {
              // debugger;
              this.resultImgurl = data.url;
              this.resultImgname = data.name;
            } else {
              throw new Error('图片上传失败，请重试！');
            }
          } else {
            throw new Error(message || '图片上传失败，请重试！');
          }
          const url = `api/file/download/${this.resultImgurl}`;
          this.currentItem.imageSrc2 = url
        }
      } catch (err) {
        this.$emit('updateSignImg', '', this.signType);
      }
    },
  }
};
</script>
<style scoped>
:deep(.el-button-print .el-button) {
  display: inline-flex !important;
  visibility: visible !important;
  opacity: 1 !important;
  width: auto;
  min-width: 100px;
  height: auto;
  padding: 8px 15px;
  background: #fff !important;
  color: #000 !important;
  border: none;
}

:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden;
  line-height: 1.3;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden !important;
  resize: none !important;
  height: auto !important;
}

.input-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inputStyleNoLine {
  border: none;
  outline: none;
  padding: 0px;
}

.typeSpan {
  cursor: pointer;
  font-size: 5mm;
}
</style>
